package org.ruiyichen.guizhou.agr.base;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore.MediaColumns;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.open.utils.ThreadManager;
import com.tencent.tauth.IUiListener;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.ruiyichen.guizhou.agr.R;
import org.ruiyichen.guizhou.agr.config.Constant;
import org.ruiyichen.guizhou.agr.net.OkHttpManager;
import org.ruiyichen.guizhou.agr.ui.mineview.BToast;
import org.ruiyichen.guizhou.agr.ui.mineview.BallProgressDialog;
import org.ruiyichen.guizhou.agr.utils.L;
import org.ruiyichen.guizhou.agr.utils.NetWorkUtils;
import org.ruiyichen.guizhou.agr.utils.StatusBarUtil;
import org.ruiyichen.guizhou.agr.utils.StrUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
import java.util.concurrent.ExecutionException;

import androidx.annotation.DrawableRes;
import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker;
import androidx.fragment.app.FragmentActivity;

import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;

/**
 * 基础类
 *
 * @author Administrator
 */
public abstract class BaseActivity extends FragmentActivity implements Observer {

    public static final String FROM_TAG = "fromClass";

    private static String TAG = BaseActivity.class.getSimpleName();


    //图片选择器--start
    protected static final int REQUEST_IMAGE = 2;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    protected static final int REQUEST_STORAGE_WRITE_ACCESS_PERMISSION = 102;
    protected static final int MAX_PIC = 6;
    //请求权限
    protected static final int OVERLAY_PERMISSION_REQ_CODE = 103;

    protected ArrayList<String> mSelectPath;
    //--end

    //	Configuration mConfiguration;
    public ActivityTack tack = ActivityTack.getInstanse();

    protected WindowManager windowManager = null;

    private WindowManager.LayoutParams windowManagerParams = null;

    // 浮动窗口
    // protected FloatView floatView = null;

    public AsyncTask currentTask;

    public BallProgressDialog loadingDialog;

    public static int widthP = -100;// 屏幕宽度

    public static int heightP = -100;


    private Context mContext;


    protected OkHttpManager bOkHttpManager;

    private QQShare mTencent;
    private IWXAPI mWxApi;

    /**
     * 隐藏键盘
     */
    public void hideSoftInputFromWindow() {
        try {
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(BaseActivity.this
                            .getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
        }
    }

    /**
     * 显示键盘
     */
    public void showSoftInputFromWindow(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(view, 0);
    }

    @Override
    protected void onCreate(Bundle icicle) {

        //将状态栏设置为绿色:#38B059
        changeStatusBarColor(R.color.color_373737);

        // Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());

        // 抓闪退log
        // CrashHandler crashHandler = CrashHandler.getInstance();
        // //注册crashHandler
        // crashHandler.init(getApplicationContext()); //发送以前没发送的报告(可选)

        super.onCreate(icicle);

        //权限获取
//                  如想让你的app在android 6.0系统上也能运行的话，需要动态获取权限，没有权限的话分享sdk会出错，参考一下代码做动态获取权限,适配安卓6.0系统
//          你需要最新的android.support.v4包，或者v13的包可也以

        //获取图片读写权限
        if (Build.VERSION.SDK_INT >= 23) {
            int hasWriteContactsPermission = PermissionChecker.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (hasWriteContactsPermission != PERMISSION_GRANTED) {
                String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
                ActivityCompat.requestPermissions(this, mPermissionList, 151);
            }
        }

        tack.addActivity(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        loadingDialog = BallProgressDialog.createDialog(this);
        loadingDialog.setCancelable(true);
        loadingDialog.setCanceledOnTouchOutside(false);

        loadingDialog.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {// 取消等待框，取消请求线程
                Log.d("BaseActivity", "loadingDialog.setOnCancelListener");
                if (currentTask != null) {
                    currentTask.cancel(true);
                }
            }
        });

        //数据管理
        DataManger.getInstance().addObserver(this);

        mContext = this;

        BToast.getInstance().init(this);
    }


    private void changeStatusBarColor(int color) {
        StatusBarUtil.setStatusBarColor(this, color);
//        StatusBarUtil.statusBarLightMode(this, StatusBarUtil.statusBarLightMode(this));
    }

    /**
     * 初始化视图
     **/

    protected abstract void initViews();

    /**
     * 初始化事件
     **/
    protected abstract void initEvents();

    @TargetApi(19)
    public void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    /**
     * 检查当前网络是否可用
     *
     * @return
     */
    public boolean isNetworkAvailable(Activity activity) {
        return NetWorkUtils.checkNetConnect(activity) != NetWorkUtils.Type.NO_NETWORK_CONNECTION;
    }


    @Override
    protected void onDestroy() {
        loadingDialog.dismiss();
        DataManger.getInstance().deleteObserver(this);

        if (null != getIntent().getIntegerArrayListExtra("actionList")) {
            Intent broadcast = new Intent(Constant.Broadcast.MY_BROADCAST);
            broadcast.putIntegerArrayListExtra("actionList", getIntent().getIntegerArrayListExtra("actionList"));
            sendBroadcast(broadcast);
            L.e("发送广播：" + new Gson().toJson(getIntent().getIntegerArrayListExtra("actionList")));
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        /**
         * 页面结束（每个Activity中都需要添加，如果有继承的父Activity中已经添加了该调用，那么子Activity中务必不能添加）
         * 不能与StatService.onPageStart一级onPageEnd函数交叉使用
         */
//		StatService.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        /**
         * 页面结束（每个Activity中都需要添加，如果有继承的父Activity中已经添加了该调用，那么子Activity中务必不能添加）
         * 不能与StatService.onPageStart一级onPageEnd函数交叉使用
         */
//		StatService.onResume(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    public void getControlcurrentThread(AsyncTask task) {
        this.currentTask = task;

    }

    public void setBackClick(boolean isCan) {
        this.isCan = isCan;
    }

    // 屏蔽返回键点击
    boolean isCan = true;


    /**
     * 通用返回事件
     *
     * @param v
     */
    public void onBackPressed(View v) {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {

        if (isCan) {
            super.onBackPressed();
        }
    }

//    public boolean checkLogin() {
//        if(DataManger.getInstance().hasLogin()){
//            return true;
//        }else {
//            Intent it = new Intent(this, VerifyLoginActivity.class);
//            startActivity(it);
//            return false;
//        }
//    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        initViews();
        initEvents();

//		View v = findViewById(R.id.back);
//		if (v != null) {
//			v.setOnClickListener(new OnClickListener() {
//
//				@Override
//				public void onClick(View v) {
//					finish();
//				}
//			});
//		}
    }

    protected BaseActivity setTitle(String title) {
        return setTitle(title, true);
    }

    // 设置标题
    protected BaseActivity setTitle(String title, boolean canBack) {
        try {
            if (StrUtil.isNotEmpty(title)) {
                findViewById(R.id.rl_normal_title).setVisibility(View.VISIBLE);
                ((TextView) findViewById(R.id.tv_normal_title)).setText(title);
            } else {
                findViewById(R.id.rl_normal_title).setVisibility(View.GONE);
            }
//        findViewById(R.id.iv_normal_setting).setVisibility(View.GONE);
//        findViewById(R.id.tv_normal_save).setVisibility(View.GONE);
            if (canBack) {
                findViewById(R.id.iv_normal_back).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onBackPressed();
                    }
                });
            }
        } catch (Exception e) {
            L.e(e.getMessage());
        }
        return this;
    }

    // 设置
    public BaseActivity setRightImage(@DrawableRes int rightRes) {
        try {
            TextView normalOther = findViewById(R.id.tv_normal_other);
            if (rightRes != 0) {
                normalOther.setCompoundDrawablesWithIntrinsicBounds(0, 0, rightRes, 0);
            } else {
                normalOther.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            }
            boolean isVisibility = rightRes != 0 || StrUtil.isNotEmpty(normalOther.getText()
                    .toString());
            normalOther.setVisibility(isVisibility ? View.VISIBLE : View.GONE);
        } catch (Exception e) {
            L.e(e.getMessage());
        }
        return this;
    }

    // 设置
    public BaseActivity setRightText(String rightText) {
        try {
            TextView normalOther = findViewById(R.id.tv_normal_other);
            if (StrUtil.isNotEmpty(rightText)) {
                ((TextView) findViewById(R.id.tv_normal_other))
                        .setText(rightText);
            } else {
                ((TextView) findViewById(R.id.tv_normal_other))
                        .setText(rightText);
            }
            Drawable[] drawables = normalOther.getCompoundDrawables();
            boolean hasDrawable = false;
            for (Drawable drawable : drawables) {
                if (drawable != null) {
                    hasDrawable = true;
                    break;
                }
            }
            boolean isVisibility = hasDrawable || StrUtil.isNotEmpty(rightText);
            normalOther.setVisibility(isVisibility ? View.VISIBLE : View.GONE);
        } catch (Exception e) {
            L.e(e.getMessage());
        }
        return this;
    }

    /**
     * 设置标题背景透明
     */
//    protected void setTitleBgTransparent() {
//        findViewById(R.id.ll_normal_title).setBackgroundColor(Color.TRANSPARENT);
//        findViewById(R.id.v_split_line).setBackgroundColor(Color.TRANSPARENT);
//    }

    // 设置标题
//    protected void setTitle(String... titles) {
//        if (titles.length == 1) {
//            setTitle(titles[0]);
//        } else if (titles.length == 2) {
//            findViewById(R.id.iv_normal_setting).setVisibility(View.GONE);
//            ((TextView) findViewById(R.id.tv_normal_title)).setText(titles[0]);
//            findViewById(R.id.tv_normal_save).setVisibility(View.VISIBLE);
//            ((TextView) findViewById(R.id.tv_normal_save)).setText(titles[1]);
//        }
//    }


    /**
     * 清理内存
     */
    public void Gc() {
        // 清除之前的activity
        ActivityTack.getInstanse().finshAllOther(getApplicationContext());
        System.gc();
    }


    protected Handler bHandler = new Handler() {

        @Override
        public void handleMessage(android.os.Message msg) {
            L.v("recevie msg = " + msg.arg2 + " msg.obj = " + msg.obj);
            // 如果是从缓存取数据
            if (loadingDialog != null && loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }

            //带进度条
            if (msg.arg2 == 100) {
                onProgressHandle(msg.what, msg.arg1, null, null);
                return;
            }

            if (msg.arg2 == 99) {
                onPostHandle(msg.what, msg.obj, false, 0, null, null);
                return;
            }
            if (msg.what == 404) {
                onPostHandle(msg.what, msg.obj, true, 0, null, null);
                return;
            }
            if (null != msg.obj) {
                onPostHandle(msg.what, msg.obj, false, 0, null, null);
            } else {
                onPostHandle(msg.what, msg.obj, false, 0, null, null);
            }
        }
    };

    @Override
    public void finish() {
        super.finish();
        tack.removeActivity(this);
        popOutAnim();
    }

    public void finish(boolean hasAnim) {
        super.finish();
        tack.removeActivity(this);
        if (hasAnim)
            popOutAnim();
    }

    @Override
    public void startActivity(Intent intent) {
//		 ActivitySplitAnimationUtil.startActivity(BaseActivity.this,intent);
//        if (null != getIntent() && StrUtil.isNotEmpty(getIntent().getSerializableExtra(FROM_TAG))) {
//            intent.putExtra(FROM_TAG, getIntent().getStringExtra(FROM_TAG));
//        }
        if (null != getIntent() && null != getIntent().getSerializableExtra(FROM_TAG)) {
            intent.putExtra(FROM_TAG, getIntent().getSerializableExtra(FROM_TAG));
        }
        super.startActivity(intent);
        popInAnim();
    }

    /**
     * 是否偶动画跳转
     *
     * @param intent
     * @param hasAnim true:有跳转动画; false:无跳转动画;
     */
    public void startActivity(Intent intent, boolean hasAnim) {
//		 ActivitySplitAnimationUtil.startActivity(BaseActivity.this,intent);
        super.startActivity(intent);
        if (hasAnim)
            popInAnim();
    }


    public void popInAnim() {
        System.out.println("BaseActivity:popInAnim");
//        overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
        overridePendingTransition(R.anim.push_right_in, R.anim.push_default);
    }

    public void popOutAnim() {
        System.out.println("BaseActivity:popOutAnim");
//        overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
        overridePendingTransition(R.anim.push_default, R.anim.push_right_out);
    }

    /**
     * <一句话功能简述> <功能详细描述>
     *
     * @param requestType 请求标示
     * @param response    返回的报文
     * @param error       是否请求失败， false为失败，true为成功
     * @param errorCode   错误标示码
     * @param obj1        备用字段1
     * @param obj2        备用字段2 最后更新时间：<date> 修改履历：<修改内容>
     */
    protected void onPostHandle(int requestType, Object response,
                                boolean error, int errorCode, Object obj1, Object obj2) {
//        if (loadingDialog != null && loadingDialog.isShowing()) {
//            loadingDialog.dismiss();
//        }
    }

    /**
     * 上传下载进度条回调
     *
     * @param requestType 请求标示
     * @param progress    进度百分比
     * @param obj1        备用字段1
     * @param obj2        备用字段2
     */
    protected void onProgressHandle(int requestType, int progress, Object obj1, Object obj2) {
    }

    /**
     * 请求数据失败提示 最后更新时间：<date> 修改履历：<修改内容>
     */
    protected void showGetFailToast() {
//		Toast.makeText(BaseActivity.this,
//				getResources().getString(R.string.get_fail), Toast.LENGTH_SHORT)
//				.show();
    }

    /**
     * 用来标识请求gallery的activity
     */
    private static final int PHOTO_PICKED_WITH_DATA = 3001;
    /**
     * 用来标识请求裁剪图片后的activity
     */
    private static final int CAMERA_CROP_DATA = 3002;
    /**
     * 用来标识请求照相功能的activity
     */
    private static final int CAMERA_WITH_DATA = 3023;

    /**
     * 拍照所存的图片名称
     */
    private String mFileName;
    /**
     * 照相机拍照得到的图片
     */
    protected File mCurrentPhotoFile;
    /**
     * 拍照的照片存储位置
     */
    private File PHOTO_DIR = null;

    /**
     * 显示获取图片布局
     */
//	public void showPop(View sportIcon) {
//		LayoutInflater inflater = LayoutInflater.from(this);
//		// 引入窗口配置文件
//		View view = inflater.inflate(R.layout.get_photo_layout, null);
//		// 创建PopupWindow对象
//		final PopupWindow pop = new PopupWindow(view,
//				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, false);
//		Button photographButton = (Button) view
//				.findViewById(R.id.photographButton);
//		Button getPhototImageButton = (Button) view
//				.findViewById(R.id.getPhototImageButton);
//		Button cancleButton = (Button) view.findViewById(R.id.cancleButton);
//		// 需要设置一下此参数，点击外边可消失
//		pop.setBackgroundDrawable(new BitmapDrawable());
//		// 设置点击窗口外边窗口消失
//		pop.setOutsideTouchable(true);
//		// 设置此参数获得焦点，否则无法点击
//		pop.setFocusable(true);
//		photographButton.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				pop.dismiss();
//				// 拍照
//				doPickPhotoAction();
//			}
//		});
//		getPhototImageButton.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View arg0) {
//				pop.dismiss();
//				Intent intent_3;
//				intent_3 = new Intent(
//						Intent.ACTION_PICK,
//						MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//				startActivityForResult(intent_3, PHOTO_PICKED_WITH_DATA);
//			}
//		});
//
//		cancleButton.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View arg0) {
//				if (pop.isShowing()) {
//					// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
//					pop.dismiss();
//				}
//			}
//		});
//		pop.showAtLocation(sportIcon, Gravity.BOTTOM, 0, 0);
//	}

//    /**
//     * 描述：从照相机获取
//     */
//    public void doPickPhotoAction() {
//        String status = Environment.getExternalStorageState();
//        // 判断是否有SD卡,如果有sd卡存入sd卡在说，没有sd卡直接转换为图片
//        if (status.equals(Environment.MEDIA_MOUNTED)) {
////            doTakePhoto();
//        } else {
//            // "没有可用的存储卡"
////			CustomToast.getInstance(this).showToast("没有可用的存储卡");
//        }
//    }


    /**
     * 从相册得到的url转换为SD卡中图片路径
     */
    public String getPath(Uri uri) {
        if (StrUtil.isEmpty(uri.getAuthority())) {
            return null;
        }
        String[] projection = {MediaColumns.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        return path;
    }


    private Display mDisp;
    private int mScreenWidth;
    private int mScreenHeight;

    /**
     * ExpandableListView动画初始化
     */
    protected TranslateAnimation taLeft, taRight, taTop, taBlow;

    protected void InitAnima() {
        taLeft = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 1.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f);
        taRight = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -1.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f);
        taTop = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 1.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f);
        taBlow = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_PARENT, -1.0f,
                Animation.RELATIVE_TO_PARENT, 0.0f);
        taLeft.setDuration(800);
        taRight.setDuration(800);
        taTop.setDuration(800);
        taBlow.setDuration(800);
    }

    /**
     * 设置item动画 设置动画前必须在onCreate里调用 InitAnima()初始化动画
     *
     * @param convertView ：动画对应的view
     */
    protected void setItemAnim(View convertView) {
        Random ran = new Random();
        int rand = ran.nextInt(4);
        switch (rand) {
            case 0:
                convertView.startAnimation(taLeft);
                break;
            case 1:
                convertView.startAnimation(taRight);
                break;
            case 2:
                convertView.startAnimation(taTop);
                break;
            case 3:
                convertView.startAnimation(taBlow);
                break;
        }
    }

    /**
     * 附文本实现一段字显示两种颜色
     *
     * @param str
     * @param keywordTypeVal
     * @return
     */
    public SpannableString getClickableSpan(String str, String keywordTypeVal) {

        SpannableString spanableInfo = new SpannableString(str + keywordTypeVal);
        int start = str.length();
        int end = spanableInfo.length();
        spanableInfo.setSpan(new ClickableSpan() {

            @Override
            public void updateDrawState(TextPaint ds) {
                // 颜色下划线等
                super.updateDrawState(ds);

                ds.setColor(Color.parseColor("#7D8E2E"));
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {

            }

        }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spanableInfo;
    }

    /**
     * 附文本实现一段字显示两种颜色
     *
     * @param str
     * @param keywordTypeVal
     * @return
     */
    public SpannableString getClickableSpan(String str, String keywordTypeVal,
                                            String strEnd) {

        SpannableString spanableInfo = new SpannableString(str + keywordTypeVal);
        int start = str.length();
        int end = spanableInfo.length();
        spanableInfo = new SpannableString(str + keywordTypeVal + strEnd);
        spanableInfo.setSpan(new ClickableSpan() {

            @Override
            public void updateDrawState(TextPaint ds) {
                // 颜色下划线等
                super.updateDrawState(ds);

                ds.setColor(Color.parseColor("#7D8E2E"));
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {

            }

        }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spanableInfo;
    }

    /**
     * 登录按钮偏移量
     */
    private int btnOffset = 0;

    /**
     * @param root         最外层布局，需要调整的布局
     * @param scrollToView 被键盘遮挡的scrollToView，滚动root,使scrollToView在root可视区域的底部
     */
    public void controlKeyboardLayouts(final View root, final View scrollToView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener(
                new OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        Rect rect = new Rect();
                        // 获取root在窗体的可视区域
                        root.getWindowVisibleDisplayFrame(rect);
                        // 获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                        int rootInvisibleHeight = root.getRootView()
                                .getHeight() - rect.bottom;
                        // 若不可视区域高度大于100，则键盘显示
                        if (rootInvisibleHeight > 100) {
                            int[] location = new int[2];
                            if (btnOffset == 0) {
                                // 获取scrollToView在窗体的坐标
                                scrollToView.getLocationInWindow(location);
                            } else {
                                location[1] = btnOffset;
                            }
                            // 计算root滚动高度，使scrollToView在可见区域
                            int scrollHeight = (location[1] + scrollToView
                                    .getHeight()) - rect.bottom;
                            root.scrollTo(0, scrollHeight);
                            btnOffset = location[1];
                        } else {
                            // 键盘隐藏
                            root.scrollTo(0, 0);
                        }
                    }
                });
    }

    /**
     * 底部滑动动画
     *
     * @param view       滑动的view
     * @param isUpOrDown 是否从上往下滑动
     * @param height     控件上拉下滑的高度
     */
    public void toUpOrDown(final View view, final boolean isUpOrDown,
                           float height) {
        // if ((!isUpOrDown && view.getVisibility() == View.VISIBLE)
        // || (isUpOrDown && view.getVisibility() == View.GONE)) {
        // return;
        // }
        // AnimationSet animationSet = new AnimationSet(true);
        // float fromYValue = 0f;
        // float toYValue = height;
        // if (!isUpOrDown) {
        // fromYValue = height;
        // toYValue = 0;
        // height = -height;
        // }
        // TranslateAnimation translateAnimation = new
        // TranslateAnimation(0,0,fromYValue,toYValue);
        // translateAnimation.setDuration(300);
        // translateAnimation.setFillAfter(true);
        // translateAnimation.setFillEnabled(true);
        // animationSet.addAnimation(translateAnimation);
        // animationSet.setAnimationListener(new AnimationListener() {
        //
        // @Override
        // public void onAnimationStart(Animation animation) {
        // if (!isUpOrDown) {
        // view.setVisibility(View.VISIBLE);
        // }
        // }
        //
        // @Override
        // public void onAnimationRepeat(Animation animation) {
        //
        // }
        //
        // @Override
        // public void onAnimationEnd(Animation animation) {
        // if (isUpOrDown) {
        // view.setVisibility(View.GONE);
        // }
        // }
        // });
        // view.startAnimation(animationSet);
    }

    /**
     * 顶部滑动动画
     *
     * @param view       滑动的view
     * @param isUpOrDown 是否从上往下滑动
     */
    public void topToUpOrDown(final View view, final boolean isUpOrDown,
                              float height) {
        // if (isUpOrDown && view.getVisibility() == View.VISIBLE) {
        // return;
        // }
        // AnimationSet animationSet = new AnimationSet(true);
        // float fromYValue = -height;
        // float toYValue = 0f;
        // if (!isUpOrDown) {
        // fromYValue = 0f;
        // toYValue = -height;
        // }
        // TranslateAnimation translateAnimation = new
        // TranslateAnimation(0,0,fromYValue,toYValue);
        // translateAnimation.setDuration(150);
        // translateAnimation.setFillAfter(true);
        // translateAnimation.setFillEnabled(true);
        // animationSet.addAnimation(translateAnimation);
        // animationSet.setAnimationListener(new AnimationListener() {
        //
        // @Override
        // public void onAnimationStart(Animation animation) {
        // if (isUpOrDown) {
        // view.setVisibility(View.VISIBLE);
        // }
        // }
        //
        // @Override
        // public void onAnimationRepeat(Animation animation) {
        //
        // }
        //
        // @Override
        // public void onAnimationEnd(Animation animation) {
        // if (!isUpOrDown) {
        // view.setVisibility(View.GONE);
        // }
        // }
        // });
        // view.startAnimation(animationSet);
    }


    /**
     * 判断是否安装微信
     *
     * @param appType 应用类型 1：微信；2：QQ；
     * @return
     */
    public boolean isApkAvilible(int appType) {
        final PackageManager packageManager = getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        String apk = "";
        switch (appType) {
            case 1:
                apk = "com.tencent.mm";
                break;
            case 2:
                apk = "com.tencent.mobileqq";
                break;
        }

        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(apk)) {
                    return true;
                }
            }
        }
        return false;
    }


    /*
     * 打开设置网络界面
     * */
    public void setNetworkMethod(final Activity activity) {
        //提示对话框
//		AlertDialog.Builder builder=new AlertDialog.Builder(context);
//		builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
//
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				Intent intent=null;
//				//判断手机系统的版本  即API大于10 就是3.0或以上版本
//				if(android.os.Build.VERSION.SDK_INT>10){
//					intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
//				}else{
//					intent = new Intent();
//					ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
//					intent.setComponent(component);
//					intent.setAction("android.intent.action.VIEW");
//				}
//				context.startActivity(intent);
//			}
//		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
//
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				dialog.dismiss();
//			}
//		}).show();

        Intent intent = null;
        if (android.os.Build.VERSION.SDK_INT > 10) {
            intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
        } else {
            intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
        }
        activity.startActivityForResult(intent, 0);
    }

    public String getDeviceId() {
        final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
        final String tmDevice, tmSerial, tmPhone, androidId;
        tmDevice = "" + tm.getDeviceId();
        return tmDevice;
    }

    /**
     * 下拉收起动画
     *
     * @param v
     * @param al
     */
    protected void collapse(final View v, Animation.AnimationListener al) {
        final int initialHeight = v.getMeasuredHeight();

        Animation anim = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                Log.e("wt", TAG + ":applyTransformation-->" + interpolatedTime);
                if (interpolatedTime == 1) {
                    v.setVisibility(View.GONE);
                } else {
                    v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
                    v.requestLayout();
                }
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };

        if (al != null) {
            anim.setAnimationListener(al);
        }
        anim.setDuration(300);
        v.startAnimation(anim);
    }

    /**
     * 分享
     *
     * @param type:分享类型      1:分享qq好友;2:分享qq空间;3:分享微信好友;4:分享微信朋友圈;
     * @param params:需要分享的内容
     */
    @Deprecated
    protected void shareOthers(int type, final Map<String, String> params, final IUiListener shareListener) {
        L.d("需要分享的内容");
        if (type == 1 || type == 2) {
            final Bundle bundle = new Bundle();
            //分享qq好友
            bundle.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            bundle.putString(QQShare.SHARE_TO_QQ_TITLE, params.get(QQShare.SHARE_TO_QQ_TITLE));
            bundle.putString(QQShare.SHARE_TO_QQ_SUMMARY, params.get(QQShare.SHARE_TO_QQ_SUMMARY));
            bundle.putString(QQShare.SHARE_TO_QQ_TARGET_URL, params.get(QQShare.SHARE_TO_QQ_TARGET_URL));
            bundle.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, params.get(QQShare.SHARE_TO_QQ_IMAGE_URL));
            bundle.putString(QQShare.SHARE_TO_QQ_APP_NAME, params.get(QQShare.SHARE_TO_QQ_APP_NAME));
            if (type == 1) {
                bundle.putInt(QQShare.SHARE_TO_QQ_EXT_INT, 0);
            } else {
                bundle.putInt(QQShare.SHARE_TO_QQ_EXT_INT, 1);
            }
            ThreadManager.getMainHandler().post(new Runnable() {

                @Override
                public void run() {
                    if (null != mTencent) {
                        mTencent.shareToQQ(BaseActivity.this, bundle, shareListener);
                    }
                }
            });


        } else {
            if (!isApkAvilible(1)) {
                BToast.getInstance().show("尚未安装微信，请安装微信后再尝试！");
                return;
            }
            WXWebpageObject webpage = new WXWebpageObject();
            webpage.webpageUrl = params.get(QQShare.SHARE_TO_QQ_TARGET_URL);
            final WXMediaMessage msg = new WXMediaMessage(webpage);
            msg.title = params.get(QQShare.SHARE_TO_QQ_TITLE);
            msg.description = params.get(QQShare.SHARE_TO_QQ_SUMMARY);

            final SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
//            Data.shareType = 1;
            if (type == 3) {
                //3:分享到微信好友
                req.scene = SendMessageToWX.Req.WXSceneSession;
            } else {
                //4:分享到微信朋友圈
                req.scene = SendMessageToWX.Req.WXSceneTimeline;
            }

            new Thread(new Runnable() {
                @Override
                public void run() {
                    Bitmap bit = null;
                    try {
                        bit = Glide.with(getApplicationContext()).load(params.get(QQShare.SHARE_TO_QQ_IMAGE_URL)).asBitmap().centerCrop().into(150, 150).get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
//                    Bitmap bit = ImageLoader.getInstance().loadImageSync(params.get(QQShare.SHARE_TO_QQ_IMAGE_URL), new ImageSize(150, 150), MyValueFix.getInstance().imageOptions(null));
                    L.e("bit:" + bit + "| imagePath:" + params.get(QQShare.SHARE_TO_QQ_IMAGE_URL));
                    msg.setThumbImage(bit);
                    req.message = msg;
                    if (mWxApi != null)
                        mWxApi.sendReq(req);
                }
            }).start();

//            Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
//            msg.setThumbImage(thumb);
//            req.message = msg;
//            if (mWxApi != null)
//                mWxApi.sendReq(req);
        }

    }


    /**
     * 分享
     *
     * @param type            分享类型
     * @param params          分享参数
     * @param umShareListener 分享监听
     */
    public void shareOthers(SHARE_MEDIA type, final Map<String, String> params, final UMShareListener umShareListener) {
        if (params == null)
            return;
        L.d("需要分享的内容:" + new Gson().toJson(params));
        UMImage image = new UMImage(this, params.get(Constant.Share.SHARE_IMAGE));
        new ShareAction(this)
                .setPlatform(type)
                .setCallback(umShareListener)
                .withTitle(params.get(Constant.Share.SHARE_TITLE))
                .withText(params.get(Constant.Share.SHARE_CONTENT))
                .withTargetUrl(params.get(Constant.Share.SHARE_URL))
                .withMedia(image)
                .share();


//        Intent sendIntent = new Intent();
//        sendIntent.setAction(Intent.ACTION_SEND);
//        sendIntent.putExtra(Intent.EXTRA_TEXT, "ssssssssss");
//        sendIntent.setType("text/plain");
//        //sendIntent.setPackage("com.tencent.mobileqq");
//        // List<ResolveInfo> rows= getShareTargets(mContext);
//        try {
////            sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");
////            sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.qfileJumpActivity");//cooperation.qqfav.widget.QfavJumpActivity
//            sendIntent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
//            Intent chooserIntent = Intent.createChooser(sendIntent, "选择分享途径");
//            if (chooserIntent == null) {
//                return;
//            }
//            mContext.startActivity(chooserIntent);
//        } catch (Exception e) {
//            mContext.startActivity(sendIntent);
//        }


//        Intent sendIntent = new Intent();
//        sendIntent.setAction(Intent.ACTION_SEND);
//        sendIntent.putExtra(Intent.EXTRA_TEXT, "sssssssss");
//        sendIntent.setType("text/plain");
//        mContext.startActivity(sendIntent);

        /*List<ResolveInfo> rows = getShareTargets(this);
        for (int i =0;i<rows.size();i++){
            L.e("ResolveInfo:"+rows.get(i).activityInfo.taskAffinity+"|"+rows.get(i).activityInfo.card_name);
        }*/
    }

    /**
     * 分享
     *
     * @param type 分享类型
     */
    public void goToOthers(SHARE_MEDIA type) {
        Intent intent;
        if (SHARE_MEDIA.QQ == type) {
            //com.tencent.mobileqq com.tencent.mobileqq.activity.HomeActivity
            intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mobileqq");
        } else {
            //com.tencent.mm           com.tencent.mm.ui.LauncherUI
            intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
//            ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
//            intent.setComponent(cmp);
        }
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, 0);
    }

    /* 获得支持ACTION_SEND的应用列表 */
    private List<ResolveInfo> getShareTargets(Context context) {
        Intent intent = new Intent(Intent.ACTION_SEND, null);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setType("text/plain");
        PackageManager pm = context.getPackageManager();
        return pm.queryIntentActivities(intent, COMPONENT_ENABLED_STATE_DEFAULT);
    }
//
//    //    图片选择
//    protected void pickImage(boolean showCamera, int maxNum, boolean canMulti) {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
//                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
//                != PackageManager.PERMISSION_GRANTED) {
//            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, getString(R.string.mis_permission_rationale),
//                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
//        } else {
////            boolean showCamera = mShowCamera.getCheckedRadioButtonId() == R.id.show;
//            if (maxNum == 0) {
//                maxNum = MAX_PIC;
//            }
//
//            MultiImageSelector selector = MultiImageSelector.create(this);
//            selector.showCamera(showCamera);
//            selector.count(maxNum);
//            if (canMulti) {
//                selector.multi();
//            } else {
//                selector.single();
//            }
//            selector.origin(mSelectPath);
//            selector.start(this, REQUEST_IMAGE);
//        }
//    }

//    private void requestPermission(final String permission, String rationale, final int requestCode) {
//        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
//            new AlertDialog.Builder(this)
//                    .setTitle(R.string.mis_permission_dialog_title)
//                    .setMessage(rationale)
//                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            ActivityCompat.requestPermissions(BaseActivity.this, new String[]{permission}, requestCode);
//                        }
//                    })
//                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
//                    .create().show();
//        } else {
//            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
//        }
//    }


//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        if (requestCode == REQUEST_STORAGE_READ_ACCESS_PERMISSION) {
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                pickImage(true, 6, true);
//            }
//        } else {
//            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        }
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(this)) {
//                    Toast.makeText(this, "权限授予失败，无法开启悬浮窗", Toast.LENGTH_SHORT).show();
                } else {
//                    Toast.makeText(this, "权限授予成功！", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void update(Observable observable, Object data) {
    }


    /**
     * 跳转首页
     *
     * @param page 跳转首页
     */
    public void goHomePage(int page) {
        //方法一
//        HomeActivity activity = (HomeActivity) ActivityTack.getInstanse().getActivityByClass(HomeActivity.class);
//        if (activity != null) {
//            activity.selectFragment(page);
//        }
//        ActivityTack.getInstanse().popUntilActivity(HomeActivity.class);
    }

    /**
     * 请求用户给予悬浮窗的权限
     */
    public void askForPermission() {
        //请求悬浮窗权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                try {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                            Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
                    Toast.makeText(this, "当前无权限，请授权！", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    L.e(e.getMessage());
                }
            }
        }
    }

    /**
     * 设置是否可以编辑
     *
     * @param editText 设置的edittext
     * @param canEdit  true 可以点击
     */
    protected void setCanEdit(EditText editText, boolean canEdit) {
        if (null == editText) return;
        editText.setFocusableInTouchMode(canEdit);
        editText.setFocusable(canEdit);
        editText.requestFocus();
    }
}
